<template>
  <div class="system-statistics-container layout-padding">
    <!-- 统计卡片 -->
    <el-row :gutter="15" class="mb15">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon client-icon">
              <el-icon size="30"><ele-Monitor /></el-icon>
            </div>
            <div class="statistics-content">
              <div class="statistics-title">客户端</div>
              <div class="statistics-number">{{ state.statistics.clients?.total || 0 }}</div>
              <div class="statistics-desc">
                活跃: {{ state.statistics.clients?.active || 0 }} | 
                禁用: {{ state.statistics.clients?.inactive || 0 }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon token-icon">
              <el-icon size="30"><ele-Key /></el-icon>
            </div>
            <div class="statistics-content">
              <div class="statistics-title">令牌</div>
              <div class="statistics-number">{{ state.statistics.tokens?.total || 0 }}</div>
              <div class="statistics-desc">
                活跃: {{ state.statistics.tokens?.active || 0 }} | 
                过期: {{ state.statistics.tokens?.expired || 0 }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon session-icon">
              <el-icon size="30"><ele-Connection /></el-icon>
            </div>
            <div class="statistics-content">
              <div class="statistics-title">会话</div>
              <div class="statistics-number">{{ state.statistics.sessions?.total || 0 }}</div>
              <div class="statistics-desc">
                活跃: {{ state.statistics.sessions?.active || 0 }} | 
                结束: {{ state.statistics.sessions?.ended || 0 }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon user-icon">
              <el-icon size="30"><ele-User /></el-icon>
            </div>
            <div class="statistics-content">
              <div class="statistics-title">用户活动</div>
              <div class="statistics-number">{{ state.statistics.users?.unique_users || 0 }}</div>
              <div class="statistics-desc">
                总登录: {{ state.statistics.users?.total_logins || 0 }} | 
                在线: {{ state.statistics.users?.active_sessions || 0 }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动统计 -->
    <el-row :gutter="15" class="mb15">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近24小时活动</span>
              <el-button type="text" @click="refreshStatistics">
                <el-icon><ele-Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
              <div class="recent-activity-item">
                <div class="activity-icon login-activity">
                  <el-icon size="24"><ele-UserFilled /></el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">登录次数</div>
                  <div class="activity-number">{{ state.statistics.recent_activity?.last_24h_logins || 0 }}</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
              <div class="recent-activity-item">
                <div class="activity-icon token-activity">
                  <el-icon size="24"><ele-Tickets /></el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">令牌颁发</div>
                  <div class="activity-number">{{ state.statistics.recent_activity?.last_24h_token_issued || 0 }}</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
              <div class="recent-activity-item">
                <div class="activity-icon error-activity">
                  <el-icon size="24"><ele-Warning /></el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">错误次数</div>
                  <div class="activity-number error-number">{{ state.statistics.recent_activity?.last_24h_errors || 0 }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="15">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover">
          <template #header>
            <span>客户端类型分布</span>
          </template>
          <div ref="clientTypeChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover">
          <template #header>
            <span>令牌状态分布</span>
          </template>
          <div ref="tokenStatusChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="15" class="mt15">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近7天活动趋势</span>
              <el-radio-group v-model="state.chartTimeRange" @change="updateTrendChart">
                <el-radio-button label="7d">7天</el-radio-button>
                <el-radio-button label="30d">30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="activityTrendChartRef" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="oidcStatistics">
import { reactive, onMounted, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { getStatistics, getActivityTrend } from '/@/api/oidc/statistics';

// 定义变量内容
const clientTypeChartRef = ref();
const tokenStatusChartRef = ref();
const activityTrendChartRef = ref();

const state = reactive({
  statistics: {
    clients: null,
    tokens: null,
    sessions: null,
    users: null,
    recent_activity: null,
  },
  chartTimeRange: '7d',
  charts: {
    clientTypeChart: null,
    tokenStatusChart: null,
    activityTrendChart: null,
  },
});

// 获取统计数据
const getStatisticsData = () => {
  getStatistics()
    .then((res: any) => {
      state.statistics = res.data;
      nextTick(() => {
        initCharts();
      });
    })
    .catch(() => {
      ElMessage.error('获取统计数据失败');
    });
};

// 刷新统计数据
const refreshStatistics = () => {
  getStatisticsData();
  ElMessage.success('数据已刷新');
};

// 初始化图表
const initCharts = () => {
  initClientTypeChart();
  initTokenStatusChart();
  initActivityTrendChart();
};

// 初始化客户端类型分布图表
const initClientTypeChart = () => {
  if (state.charts.clientTypeChart) {
    state.charts.clientTypeChart.dispose();
  }
  
  state.charts.clientTypeChart = echarts.init(clientTypeChartRef.value);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '客户端类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: state.statistics.clients?.active || 0, name: '活跃客户端' },
          { value: state.statistics.clients?.inactive || 0, name: '禁用客户端' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  state.charts.clientTypeChart.setOption(option);
};

// 初始化令牌状态分布图表
const initTokenStatusChart = () => {
  if (state.charts.tokenStatusChart) {
    state.charts.tokenStatusChart.dispose();
  }
  
  state.charts.tokenStatusChart = echarts.init(tokenStatusChartRef.value);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '令牌状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: state.statistics.tokens?.active || 0, name: '活跃令牌' },
          { value: state.statistics.tokens?.expired || 0, name: '过期令牌' },
          { value: state.statistics.tokens?.revoked || 0, name: '撤销令牌' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  state.charts.tokenStatusChart.setOption(option);
};

// 初始化活动趋势图表
const initActivityTrendChart = () => {
  // if (state.charts.activityTrendChart) {
  //   state.charts.activityTrendChart.dispose();
  // }
  
  // state.charts.activityTrendChart = echarts.init(activityTrendChartRef.value);
  
  // // 获取趋势数据
  // getActivityTrend({ range: state.chartTimeRange })
  //   .then((res: any) => {
  //     const data = res.data;
  //     const dates = data.map((item: any) => item.date);
  //     const logins = data.map((item: any) => item.logins);
  //     const tokenIssued = data.map((item: any) => item.token_issued);
  //     const errors = data.map((item: any) => item.errors);
      
  //     const option = {
  //       tooltip: {
  //         trigger: 'axis'
  //       },
  //       legend: {
  //         data: ['登录次数', '令牌颁发', '错误次数']
  //       },
  //       grid: {
  //         left: '3%',
  //         right: '4%',
  //         bottom: '3%',
  //         containLabel: true
  //       },
  //       xAxis: {
  //         type: 'category',
  //         boundaryGap: false,
  //         data: dates
  //       },
  //       yAxis: {
  //         type: 'value'
  //       },
  //       series: [
  //         {
  //           name: '登录次数',
  //           type: 'line',
  //           stack: 'Total',
  //           data: logins,
  //           smooth: true,
  //           itemStyle: {
  //             color: '#67C23A'
  //           }
  //         },
  //         {
  //           name: '令牌颁发',
  //           type: 'line',
  //           stack: 'Total',
  //           data: tokenIssued,
  //           smooth: true,
  //           itemStyle: {
  //             color: '#409EFF'
  //           }
  //         },
  //         {
  //           name: '错误次数',
  //           type: 'line',
  //           stack: 'Total',
  //           data: errors,
  //           smooth: true,
  //           itemStyle: {
  //             color: '#F56C6C'
  //           }
  //         }
  //       ]
  //     };
      
  //     state.charts.activityTrendChart.setOption(option);
  //   })
  //   .catch(() => {
  //     ElMessage.error('获取趋势数据失败');
  //   });
};

// 更新趋势图表
const updateTrendChart = () => {
  initActivityTrendChart();
};

// 页面加载时
onMounted(() => {
  getStatisticsData();
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (state.charts.clientTypeChart) {
      state.charts.clientTypeChart.resize();
    }
    if (state.charts.tokenStatusChart) {
      state.charts.tokenStatusChart.resize();
    }
    if (state.charts.activityTrendChart) {
      state.charts.activityTrendChart.resize();
    }
  });
});
</script>

<style scoped lang="scss">
.system-statistics-container {
  .statistics-card {
    .statistics-item {
      display: flex;
      align-items: center;
      
      .statistics-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        
        &.client-icon {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
        }
        
        &.token-icon {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          color: white;
        }
        
        &.session-icon {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          color: white;
        }
        
        &.user-icon {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          color: white;
        }
      }
      
      .statistics-content {
        flex: 1;
        
        .statistics-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 5px;
        }
        
        .statistics-number {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;
        }
        
        .statistics-desc {
          font-size: 12px;
          color: #C0C4CC;
        }
      }
    }
  }
  
  .recent-activity-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border-radius: 8px;
    background-color: #f8f9fa;
    
    .activity-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      
      &.login-activity {
        background-color: #67C23A;
        color: white;
      }
      
      &.token-activity {
        background-color: #409EFF;
        color: white;
      }
      
      &.error-activity {
        background-color: #F56C6C;
        color: white;
      }
    }
    
    .activity-content {
      .activity-title {
        font-size: 14px;
        color: #606266;
        margin-bottom: 5px;
      }
      
      .activity-number {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
        
        &.error-number {
          color: #F56C6C;
        }
      }
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>